<?php

namespace addons\shopro\listener\order;

use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use addons\shopro\model\User;
use addons\shopro\model\UserWalletLog;
use addons\shopro\model\Giftlog;
use app\common\model\RetailConfig;
use app\common\model\RetailUser;
use think\Db;
use think\Exception;

/**
 * 订单确认收货后
 */
class Retail
{
    //TODO 订单确认收货后进行分佣
    public function orderFinish(&$params)
    {
        $order = $params['order'];
        $order = Order::where('id', $order['id'])->find();

        //判断是否是分享后购买的
        if(empty($order['share_user_id']) || $order['share_user_id'] == $order['user_id']){
            //自购省
            $share_user_id = $order['user_id'];
        }else{
            $share_user_id = $order['share_user_id'];
        }

        // 订单商品集合
        $confirmGoods = OrderItem::where('order_id', $order['id'])->where('dispatch_status', '=', OrderItem::DISPATCH_STATUS_NOSEND)->select();

        //计算佣金,商品总价goods_amount,成本总价goods_cost_amount
        $goods_amount = 0;
        $goods_cost_amount = 0;
        $commission = 0;
        foreach ($confirmGoods as $item){
            $commission = $item['commission'] * $item['goods_num'] + $commission;

            $goods_amount = $item['goods_price'] * $item['goods_num'] + $goods_amount;

            $goods_cost_amount = $item['cost_price'] * $item['goods_num'] + $goods_cost_amount;
        }
        if(empty($commission)){
            //没有佣金
            return;
        }

        $userModel = new User();

        //分享人信息
        $user = clone $userModel;
        $user = $user->find($share_user_id);

        //判断是否有上级,计算上级分佣
        $parent_commission = 0;
        $retail_parent = null;
        $retail_user = db('retail_user')->find($user->id);
        if(!empty($retail_user) && $retail_user['pid']){
            //直属上级会员
            $retailUserModel = new RetailUser();
            $retail_parent = $retailUserModel->getUserInfo($retail_user['pid']);

            //分配给直属上级X元,retail_config.under_wanjia,根据B的等级来决定给多少推荐奖励
            $retailConfigModel = new RetailConfig();
            $conf   = $retailConfigModel->getRecommendConfig("under_wanjia");

            //计算上级分佣
            if($retail_parent && !empty($conf[$retail_parent['level']])){
                $parent_commission = $commission * $conf[$retail_parent['level']] / 100;
            }
        }

        //净利润
        $profit =  $goods_amount - $goods_cost_amount;

        //平台收益 = 净利润-佣金-直属上级佣金
        $platform_profit = $profit - $commission - $parent_commission;

        $orderCommissionData = [
            'share_user_id' => $share_user_id,
            'order_id'=>$order['id'],
            'order_sn'=>$order['order_sn'],
            'goods_amount' => $goods_amount,
            'profit' => $profit,
            'commission' =>$commission,
            'parent_id' => $retail_parent['uid'] ?? 0,
            'parent_commission' => $parent_commission,
            'parent_level' => $retail_parent['level'] ?? 0,
            'platform_profit' => $platform_profit,
            'create_time'=>time(),
        ];

        $WalletModel = new UserWalletLog();
        DB::startTrans();
        try{
            //分享人
            db('user')->where(['id'=>$user['id']])->setInc('money',$commission);

            $userWallet = clone $WalletModel;
            $userWallet->doAdd($user, $commission, "sale_reward", $order['id'], "money", 1);

            if($retail_user){
                //计算累计收益
                db('retail_user')->where(['uid'=>$user['id']])->setInc('total_income',$commission);
            }

            //分享人上级
            if(!empty($parent_commission)){
                db('user')->where(['id'=>$retail_parent['uid']])->setInc('money',$parent_commission);

                db('retail_user')->where(['uid'=>$retail_parent['uid']])->setInc('total_income',$parent_commission);

                $userParent = clone $userModel;
                $parent = $userParent->find($retail_parent['uid']);

                $parentWallet = clone $WalletModel;
                $parentWallet->doAdd($parent, $parent_commission, "sale_reward_zhishu", $order['id'], "money", 1);
            }

            //订单分佣
            db('retail_order_commission')->insert($orderCommissionData);

            Db::commit();
        }catch (\Exception $e){
            \think\Log::error("商品分佣报错:".$e->getMessage());
            DB::rollback();
        }

        //团队收益分成
        RetailUser::teamReward($retail_user,$commission,$order['id']);

        //if(!empty($parent_commission)){
        //    RetailUser::teamReward($retail_parent,$parent_commission,$order['id']);
        //}

        return $order;
    }

    // 订单确认收货后,判断是否购买了高级礼包,是否可以升级成玩客
    public function orderFinishGift(&$params)
    {
        $order = $params['order'];
        $order = Order::where('id', $order['id'])->find();
        $user_id = $order['user_id'];

        // 订单商品ID集合
        $confirmGoodsIds = OrderItem::where('order_id', $order['id'])->where('dispatch_status', '=', OrderItem::DISPATCH_STATUS_NOSEND)->column('goods_id');

        //判断商品是否属于高级礼包retail_gift.goods_id
        $giftList = db('retail_gift')->where(['goods_id'=>['in',$confirmGoodsIds]])->select();

        if($giftList && ($order['activity_type'] == 'gift' || $order['activity_type'] == 'travel')){
            /*---TODO 礼包购买之后的逻辑-----*/
            $giftModel = new Giftlog();
            $type    = $giftList['0']['type'];
            $gift_id = $giftList['0']['id']; 
            $giftLog = [
                'user_id'   =>$order['user_id'],
                'order_id'  =>$order['id'],
                'gift_id'   =>$gift_id,
                'type'      =>$type,
                'total_fee' =>$order['total_fee'],
                'is_big'    =>1,
                'createtime'=>time(),
            ];
            $giftModel::insertGiftlog($giftLog);

            /*--------- END ------------*/

            //因为购买了礼包所以开始晋级玩客,以后可以改成Hook
            $this->upgrade($user_id,$order['id']);

        }else{
            //判断玩家购买的是否为配送的小礼包
            $giveList = db('retail_gift_give')->where(['goods_id'=>['in',$confirmGoodsIds]])->select();
            if($giveList && ($order['activity_type'] == 'lgift' || $order['activity_type'] == 'ltravel')){
                $giftModel = new Giftlog();
                $type    = $giveList['0']['type'];
                $gift_id = $giveList['0']['id']; 
                $giftLog = [
                    'user_id'   =>$order['user_id'],
                    'order_id'  =>$order['id'],
                    'gift_id'   =>$gift_id,
                    'type'      =>$type,
                    'total_fee' =>$order['total_fee'],
                    'is_big'    =>0,
                    'createtime'=>time(),
                ];
                $giftModel::insertGiftlog($giftLog);

                //给分享人奖励固定金额
                if(!empty($order['share_user_id']) && $order['share_user_id'] != $order['user_id']){
                    $travel_money = db('config')->where(['name'=>'travel_reward'])->value('value');
                    $travel_money = $travel_money ?? 0;

                    DB::startTrans();
                    try{
                        db('user')->where(['id'=>$order['share_user_id']])->setInc('money',$travel_money);

                        db('retail_user')->where(['uid'=>$order['share_user_id']])->setInc('total_income',$travel_money);

                        $userModel = new User();
                        $shareUser = $userModel->find($order['share_user_id']);

                        $userWallet = new UserWalletLog();
                        $userWallet->doAdd($shareUser, $travel_money, "travel_reward", $order['id'], "money", 1);
                        Db::commit();
                    }catch (\Exception $e){
                        \think\Log::error("给分享人奖励固定金额:".$e->getMessage());
                        DB::rollback();
                    }
                }
            }
        }
        return 1;
    }


    /**
     * 粉丝晋级接口
     *
     * @param string order_id 订单号
     * @param string user_id 用户ID
     */
    protected function upgrade($user_id,$order_id)
    {
        //判断用户当前等级,如果不是粉丝则跳过
        $userModel = new User();
        $model = new RetailUser();
        $retailUser = $model->getUserInfo($user_id);
        if(empty($retailUser) || $retailUser['level'] != RetailUser::LEVEL_FENS){
            //不是粉丝不能晋级
            return 0;
        }

        //1.粉丝变成玩客
        $saveData = [
            'level' => RetailUser::LEVEL_WANKE,
            'level_time' => time(),
        ];
        $retailUser = array_merge($retailUser,$saveData);
        db('retail_user')->where(['uid'=>$retailUser['uid']])->update($saveData);

        //2.奖金池
        RetailUser::insReward($retailUser);

        //3. 分配给直属上级X元,retail_config.recommend字段,根据B的等级来决定给多少推荐奖励
        $parent = $model->getUserInfo($retailUser['pid']);

        //奖励配置
        $retailConfigModel = new RetailConfig();
        $conf   = $retailConfigModel->getRecommendConfig();

        //销售佣金分成
        $under_wanjia_conf   = $retailConfigModel->getRecommendConfig("under_wanjia");

        /***************循环判断所有上级是否满足晋级条件**************/
        $child         = $retailUser;
        $is_zhishu     = true;//是否是直属下级晋级
        $acc_up_wanke  = 1;//累计晋级玩客
        $acc_up_wanzhu = 0;//累计晋级玩主
        $acc_up_wanjia = 0;//累计晋级玩家
        $is_give_reward= 1;//判断是否给了上级推荐奖励

        while( !empty($parent)){

            //下级销售收入奖励
            if(!empty($give_money) && $parent['level'] > RetailUser::LEVEL_FENS){
                //给予上级的上级销售收入奖励
                $parent_commission = $give_money * $under_wanjia_conf[$parent['level']] / 100;

                db('user')->where(['id'=>$parent['uid']])->setInc('money',$parent_commission);

                db('retail_user')->where(['uid'=>$parent['uid']])->setInc('total_income',$parent_commission);

                $userParent = clone $userModel;
                $parentGive = $userParent->find($parent['uid']);

                $parentWallet = new UserWalletLog();
                $parentWallet->doAdd($parentGive, $parent_commission, "sale_reward_zhishu", $order_id, "money", 1);
            }

            $updata = [];//更新的数据
            $give_money = 0;

            if($parent['level'] > RetailUser::LEVEL_FENS && $is_give_reward){
                /*--------粉丝升级玩客的时候给予上级奖励--------*/
                $give_money = $conf[$parent['level']];
                Db::startTrans();
                try{
                    $user = clone $userModel;
                    $useradd = $user->find($parent['uid']);
                    //钱包余额
                    db('user')->where(['id'=>$useradd->id])->setInc('money',$give_money);
                    //计算累计收益
                    db('retail_user')->where(['uid'=>$useradd->id])->setInc('total_income',$give_money);

                    $model = new UserWalletLog();
                    $model->doAdd($useradd, $give_money, "recommend", $retailUser['uid'], "money", 1);



                    Db::commit();
                }catch (\Exception $e){
                    \think\Log::error("直属晋级赠送报错:".$e->getMessage());
                    DB::rollback();
                }
                $is_give_reward = 0;

                //团队收益分成
                RetailUser::teamReward($parent,$give_money,$order_id);
            }

            $updata['wanke_num']    = $parent['wanke_num'];
            $updata['wanzhu_num']   = $parent['wanzhu_num'];
            $updata['wanjia_num']   = $parent['wanjia_num'];

            //判断下级的等级来决定上级直属下级的数量
            switch($child['level']){
                case RetailUser::LEVEL_WANKE:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanke_num']    = $parent['wanke_num'] + $zhishu_num;
                    break;
                case RetailUser::LEVEL_WANZHU:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanzhu_num'] = $parent['wanzhu_num'] + $zhishu_num;
                    break;
                case RetailUser::LEVEL_WANJIA:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanjia_num'] = $parent['wanjia_num'] + $zhishu_num;
                    break;
            }

            //累计
            $updata['wanke_total']   = $parent['wanke_total'] + $acc_up_wanke;
            $updata['wanzhu_total']  = $parent['wanzhu_total'] + $acc_up_wanzhu;
            $updata['wanjia_total']  = $parent['wanjia_total'] + $acc_up_wanjia;

            if($child['level'] != RetailUser::LEVEL_FENS){
                //判断晋级条件
                switch($parent['level']){
                    case RetailUser::LEVEL_WANKE:
                        if($updata['wanke_num'] >= RetailUser::UP_WANKE && $updata['wanke_total'] >= RetailUser::UP_WANKE_TOTAL){
                            //可以晋升,满足晋升条件
                            $updata['level'] = RetailUser::LEVEL_WANZHU;
                            $updata['level_time'] = time();

                            $acc_up_wanzhu++;
                            $is_zhishu = true;
                        }else{
                            //下一个上级就不是直属了;
                            $is_zhishu = false;
                        }
                        break;
                    case RetailUser::LEVEL_WANZHU:
                        if($updata['wanke_num'] >= RetailUser::UP_WANZHU
                            && $updata['wanke_total'] >= RetailUser::UP_WANZHU_TOTAL
                            && $updata['wanzhu_num'] >= RetailUser::UP_WANZHU_ZHISHU){
                            //可以晋升,满足晋升条件
                            $updata['level'] = RetailUser::LEVEL_WANJIA;
                            $updata['level_time'] = time();

                            $acc_up_wanjia++;
                            $is_zhishu = true;
                        }else{
                            //下一个上级就不是直属了;
                            $is_zhishu = false;
                        }
                        break;
                    case RetailUser::LEVEL_WANJIA:
                        $is_zhishu = false;
                        break;
                    default:
                        $is_zhishu = false;
                        break;
                }
            }else{
                $is_zhishu = false;
            }


            //更新上级数据
            $parent = array_merge($parent,$updata);
            db('retail_user')->where(['uid'=>$parent['uid']])->update($updata);

            //继续获取下一个上级信息
            $child  = $parent;
            $parent = db('retail_user')->where(['uid'=>$parent['pid']])->find();
        }

        return 1;
    }
}
